<template>
    <div class="database-box">
        <div class="database-body">
            <dbant-tabs v-bind:value="activeTab" @tab-change="sqlPreviewHandle">
                <el-tab-pane label="基础" name="base" :closable="false" class="database-body-base">
                    <el-scrollbar>
                        <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
                            <el-form-item label="数据库名" prop="catalogName">
                                <el-input v-model="form.catalogName" clearable :disabled="props.catalogName"></el-input>
                            </el-form-item>
                            <el-form-item label="字符集">
                                <el-select v-model="form.charset" placeholder="请选择字符集" style="width: 100%;" filterable 
                                    @change="charsetChangeHandle" clearable>
                                    <el-option :label="item.name" :value="item.name"
                                        v-for="item in characterSets"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="排序规则">
                                <el-select v-model="form.collation" placeholder="请选择排序规则" style="width: 100%;" clearable filterable >
                                    <el-option :label="item.name" :value="item.name"
                                        v-for="item in charsetChildrenList"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane label="sql预览" name="sqlPreview" :closable="false" @click="sqlPreviewHandle">
                    <el-scrollbar>
                        <div class="database-body-sql">
                            <el-input v-model="sqlPreviewValue" input-style="height:100%;flex:1" type="textarea" />
                        </div>

                    </el-scrollbar>
                </el-tab-pane>
            </dbant-tabs>
        </div>
        <div class="database-footer">
            <el-button @click="canclCreateHandle">取 消</el-button>
            <el-button type="primary" @click="submitCreateHandle">确 定</el-button>
        </div>
    </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, inject, toRefs, reactive } from "vue"
import { characterSets } from "../service/constant"
import { SqlBuilder } from '../service/SqlBuilder'
const activeTab = ref('base');
const $request = inject('$request');
const $message = inject('$message');
const $bus = inject("$bus")
const $config = inject("$config")
const sqlBuilder = new SqlBuilder();
const sqlPreviewValue = ref('');
const formRef = ref(null)
const charsetChildrenList = ref([])
const props = defineProps({
    connId:{
        type: [String, Number],
        required:true,
        default:undefined
    },
    catalogName: {
        type: String,
        default: undefined
    },
    charset: {
        type: String,
        default: undefined
    },
    collation: {
        type: String,
        default: undefined
    }

});
const form = reactive({
    catalogName: props.catalogName,
    charset: props.charset,
    collation: props.collation,
});

const rules = {
    catalogName: [
        { required: true, message: '请输入数据库名', trigger: 'blur' },
    ]
}
const emit = defineEmits(['closeDialog'])
const canclCreateHandle = () => {
    emit('closeDialog')
}
const charsetChangeHandle = (value) => {
     charsetChildrenList.value = []
     form.collation = ''
    const childrenList = characterSets.filter(item => item.name == value);
    if (childrenList && childrenList.length > 0) {
        charsetChildrenList.value = childrenList[0].children;
    }


}

const sqlPreviewHandle = (tabName) => {
    if (tabName === 'sqlPreview') {
        buildSql();

    }
}

const buildSql =  ()=>{
    if (props.catalogName) {
        sqlPreviewValue.value = sqlBuilder.alterDatabaseCovert(form.catalogName, form.charset, form.collation);
    } else {
        sqlPreviewValue.value = sqlBuilder.createDatabaseCovert(form.catalogName, form.charset, form.collation);
    }
}

const submitCreateHandle = async () => {
    await formRef.value.validate((valid) => {
        if (valid) {
            buildSql();
            const executeParams = { script: sqlPreviewValue.value };
            const params = { connId: props.connId, executeParams: executeParams };
            $request.post(`/sqlDatabase/executeScript`, params)
                .then((res) => {
                    //没有数据就设置空数据
                    if (!res.data) {
                        return;
                    }
                    const result = res.data[0];
                    if (result.success) {
                        $message.success('创建成功');
                           //刷新列表
                        $bus.$emit($config.REFRESH_PARENT_NODE)
                        canclCreateHandle();
                    } else {
                        $message.error(result.message);
                    }

                })
        }
    })
}
const queryCharset = () => {
    const params = { connId: connId.value };
    //请求后台获取子节点数据

    $request.post(`/metadata/executeFunction`, {
        type: 'charset',
        params: params,
    })
        .then((res) => {
            //没有数据就设置空数据
            if (!res.data) {
                return;
            }
            charsetList.value = res.data;
            console.log(charsetList.value)

        })
}

const charsetChangeInit = ()=>{
    if(props.charset){
        const childrenList = characterSets.filter(item => item.name == props.charset);
    if (childrenList && childrenList.length > 0) {
        charsetChildrenList.value = childrenList[0].children;
    }
    }
   
}
charsetChangeInit();
// queryCharset();
</script>
<style lang="scss" scoped>
.database-box {
    display: flex;
    flex-direction: column;
    height: 100%;

    .database-body {
        overflow: auto;
        flex: 1;
        height: 100%;

        .database-body-base {
            height: 300px;
        }

        .database-body-sql {
            height: 300px;
        }
    }

    .database-footer {
        height: 40px;
        display: flex;
        flex-direction: row-reverse;

        .el-button {
            margin: 10px 10px 0px 10px
        }

    }
}
</style>